<template>
  <div id="gengxin">
    <div class="step-one">
      <div class="one-title">
        <div class="all-title">更新知识图谱</div>
        <div class="one-btns">
          <div
            class="all-btn"
            @click="$router.push('/zhishi')"
          >
            <el-icon>
              <ArrowLeft />
            </el-icon>
            返回上一级
          </div>
        </div>
      </div>
      <div
        v-show="!loading"
        class="one-main"
      >
        <!-- 
          文件上传组件：支持上传 PDF 文件到 /dify/upload 接口。
          
          属性说明：
          - ref="upload": 引用 el-upload 组件实例，用于后续操作（如手动触发上传）。
          - action="/dify/upload": 指定文件上传的目标 API 地址。
          - :data="{ bookInfoId: 1 }": 额外的请求参数，这里传递了 bookInfoId=1。
          - :on-success="handleSuccess": 文件上传成功后的回调函数。
          - :on-error="handleError": 文件上传失败后的回调函数。
          - :before-upload="beforeUpload": 在文件上传前执行的钩子函数，通常用于校验文件类型和大小。
          - :limit="1": 限制一次最多只能上传一个文件。
          - accept=".pdf": 只允许选择 PDF 格式的文件。
          - :auto-upload="true": 自动上传，选择文件后立即上传，如果设置为 false，则需要手动调用 upload 方法来触发上传。
        -->
        <el-upload
          ref="upload"
          class="avatar-uploader"
          :key="uploadKey"
          action="/dev/dify/upload"
          :data="{ bookInfoId: 1 }"
          :show-file-list="false"
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
          :on-error="handleError"
          :limit="1"
          accept=".pdf"
          :auto-upload="true"
          :http-request="customUpload"
          drag
        >
          <div class="upload-box">
            <div class="box-one">
              <div class="img-box">
                <img src="@/assets/img/zhishi/upload.png">
              </div>
              <div class="one-txt">导入本地文档，点击上传或拖拽文件到这里</div>
              <div class="one-subtxt">支持PDF（带目录的教材书籍），每个文件不超过 50MB。</div>
            </div>
            <div class="box-two">
              <div class="two-txt">上传书籍中确保有目录哦~ 例如：</div>
              <div>
                <img src="@/assets/img/zhishi/upload-info.png">
              </div>
            </div>
          </div>
        </el-upload>
        <div class="file-list">
          <div
            v-for="item in PDFList"
            :key="item.id"
          >
            <div class="file-left">
              <div>
                <img
                  src="@/assets/img/zhishi/pdf.png"
                  alt="PDF 图标"
                >
              </div>
              <div class="file-title">{{ item.fileName }}</div>
            </div>
            <div class="file-right">
              <div class="file-size">{{ item.fileSize }}</div>
              <div class="file-type">
                <div v-if="item.status === '0'">
                  <img
                    src="@/assets/img/zhishi/weishengcheng.png"
                    alt="未生成图标"
                  >
                  未生成
                </div>
                <div v-else-if="item.status === '1'">
                  <!-- <img
                    src="@/assets/img/zhishi/weishengcheng.png"
                    alt="构建成功图标"
                  > -->
                  <el-icon
                    color="green"
                    size="16"
                  >
                    <Check />
                  </el-icon>
                  <span style="color: green">构建成功</span>
                </div>
                <div v-else-if="item.status === '2'">
                  <img
                    src="@/assets/img/zhishi/weishengcheng.png"
                    alt="生成中图标"
                  >
                  生成中
                </div>
                <div v-else-if="item.status === '3'">
                  <img
                    src="@/assets/img/zhishi/weishengcheng.png"
                    alt="生成失败图标"
                  >
                  生成失败
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    placement="bottom-start"
                  >
                    <template #content>
                      <div style="width: 200px;">
                        本次生成操作于第20页处中断。后续继续进行生成时，将从第20页起始，直至文档末页。
                      </div>
                    </template>
                    <img
                      src="@/assets/img/zhishi/tishi.png"
                      alt="提示图标"
                    >
                  </el-tooltip>
                </div>
              </div>
              <!-- 生成图谱按钮 -->
              <div>
                <div
                  class="file-btn"
                  :class="{ 'disabled-btn': ![0, 3].includes(Number(item.status)) }"
                  @click="handleGenerateGraph(item)"
                >
                  <img
                    src="@/assets/img/zhishi/ai.png"
                    alt="生成图谱图标"
                  >
                  生成图谱
                </div>
              </div>
              <div
                class="flie-close"
                @click="deletePDF(item)"
              >
                <img
                  src="@/assets/img/zhishi/close.png"
                  alt="关闭图标"
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div
      v-if="loading"
      class="loading"
    >
      <div class="all-box">
        <div class="loading-img">
          <img src="@/assets/img/zhishi/loading.png">
        </div>
        <div class="loading-title">AI正在构建您的知识图谱，请保持页面开启</div>
        <div class="loading-subtitle">本次生成知识图谱时，知识点应进行增量更新，确保原有数据不被覆盖。</div>
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      width="550"
      :before-close="handleClose"
    >
      <div class="my-dialog">
        <div class="my-dialog-title">
          <img src="@/assets/img/zhishi/jiqiren.png">
          为了提高解析的精确度，请告诉我目录列表在书籍中的页码范围。
        </div>
        <div class="my-dialog-content">
          <div>第</div>
          <div>
            <el-input-number
              v-model="startPage"
              :min="1"
              :max="10"
              :step="1"
              step-strictly
              @change="handleChange"
            />
          </div>
          <div>页至第</div>
          <div>
            <el-input-number
              v-model="endPage"
              :min="1"
              :step="1"
              step-strictly
              @change="handleChange"
            />
          </div>
          <div>页</div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            color="#155EEF"
            @click="analysisPDF()"
          >
            确定
          </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
    
<script>
export default {
  data() {
    return {
      uploadKey: 0, // 动态 key
      PDFList: [],
      loading: false,
      dialogVisible: false,
      imageUrl: "",
      num: 1,
      fileId: "",
      startPage: 7,
      endPage: 12,
    };
  },
  created() {
    this.getPDFList();
  },
  methods: {
    clearPDFInfo() {
      this.fileId = "";
      this.startPage = 7;
      this.endPage = 12;
    },
    //处理生成图谱按钮的点击事件
    handleGenerateGraph(item) {
      const allowedStatuses = [0, 3]; // 允许的状态：未生成 (0) 和 生成失败 (3)
      if (!allowedStatuses.includes(Number(item.status))) {
        this.$message.warning("当前状态不允许生成图谱！");
        return;
      }
      this.clearPDFInfo();
      this.fileId = item.id;
      this.dialogVisible = true;
    },
    analysisPDF() {
      const url = `/dify/startProcess?fileId=${this.fileId}&startPage=${
        this.startPage || 5
      }&endPage=${this.endPage || 8}`;
      this.dialogVisible = false;
      this.loading = true;
      // 执行生成图谱的逻辑
      this.$message.success("正在生成图谱，请稍候...");
      this.$axios
        .post(url)
        .then((response) => {
          const res = response;
          console.log(res, 1);
          if (res.code === 200) {
            this.PDFList = res.data;
          } else {
            this.$message.error(res.msg || "获取失败，请稍后重试");
          }
          this.loading = false;
          this.getPDFList();
        })
        .catch((error) => {
          this.$message.error(error.message || "获取失败，请稍后重试");
          this.loading = false;
          this.getPDFList();
        });
    },
    //删除PDF文件
    deletePDF(item) {
      const url = `/dify/pdf/delete?id=${item.id}`;
      //删除前确认
      this.$confirm("确定要删除该文件吗？")
        .then(() => {
          this.$axios.delete(url).then((response) => {
            const res = response;
            this.$message.error(res.msg || "删除成功");
            this.getPDFList();
          });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    //获取pdf列表
    getPDFList() {
      const url = "/dify/pdf/history";
      const params = {
        bookInfoId: 1, // 使用 params 传递查询参数
      };
      this.$axios
        .get(url, {
          params, // 将参数传递给 `params` 属性
        })
        .then((response) => {
          const res = response;
          this.PDFList = res.data;
        });
    },
    //自定义上传
    customUpload(options) {
      const { file, data } = options;
      // 创建 FormData 对象
      const formData = new FormData();
      formData.append("file", file); // 添加文件

      for (const key in data) {
        formData.append(key, data[key]); // 添加额外参数（如 bookInfoId）
      }
      // 显示“上传中”提示
      const loadingMessage = this.$message({
        message: "上传中，请稍候...",
        type: "info",
        duration: 0, // 设置为 0 表示不自动关闭
      });
      // 使用全局挂载的 $axios 实例发起上传请求
      this.$axios
        .post("/dify/upload", formData)
        .then((response) => {
          this.handleSuccess(response, file); // 调用成功回调
          this.getPDFList();
        })
        .catch((error) => {
          this.handleError(error, file); // 调用失败回调
        })
        .finally(() => {
          // 关闭“上传中”提示
          loadingMessage.close();
        });
    },
    handleSuccess(res, file) {
      console.log("上传成功：", res);
      this.$message.success("上传成功!");
      this.uploadKey += 1; // 修改 key 值，强制重新渲染组件
    },
    beforeUpload(file) {
      // 检查是否为 PDF 文件
      const isPDF = file.type === "application/pdf";
      // 检查文件大小是否小于 2MB
      const isLt2M = file.size / 1024 / 1024 < 200;
      if (!isPDF) {
        this.$message.error("只能上传 PDF 文件！");
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 2MB！");
      }

      return isPDF && isLt2M; // 返回校验结果
    },
    handleError() {
      this.uploadKey += 1; // 修改 key 值，强制重新渲染组件
    },
    handleClose() {
      this.dialogVisible = false;
    },
    handleChange(val) {
      console.log(val);
    },
  },
};
</script>
  <style lang="scss" scoped>
#gengxin {
  margin-bottom: 20px;
  .step-one {
    .one-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      .all-title {
        margin-bottom: 0;
      }
    }
    .one-main {
      .avatar-uploader {
        :deep(.el-upload) {
          width: 100%;
          background: #ffffff;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          .upload-box {
            width: 100%;
            border-radius: 10px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 50px 0;
            > div {
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
            }
            .box-one {
              width: 60%;
              border-bottom: 1px solid #efefef;
              gap: 11px;
              padding-bottom: 23px;
              margin-bottom: 29px;
              .img-box {
                margin-bottom: 20px;
              }
              .one-txt {
                font-size: 16px;
                color: #6b6a76;
              }
              .one-subtxt {
                font-size: 14px;
                color: #a2a0b3;
              }
            }
            .box-two {
              .two-txt {
                font-size: 14px;
                color: #5f6feb;
                margin-bottom: 12px;
              }
            }
          }
        }
        margin-bottom: 10px;
      }
      .file-list {
        > div {
          display: flex;
          justify-content: space-between;
          align-items: center;
          height: 70px;
          background: #ffffff;
          border-radius: 10px;
          border: 1px solid #e4e3e4;
          margin-bottom: 10px;
          .file-left {
            display: flex;
            align-items: center;
            gap: 20px;
            padding-left: 54px;
            .file-title {
              font-weight: 400;
              font-size: 14px;
              color: #383743;
            }
          }
          .file-right {
            display: flex;
            align-items: center;
            gap: 40px;
            padding-right: 30px;
            .file-size {
              font-size: 12px;
              color: #676674;
            }
            .file-type {
              width: 80px;
              font-size: 12px;
              color: #676674;
              > div {
                display: flex;
                align-items: center;
                gap: 6px;
              }
            }
            .file-btn {
              display: flex;
              justify-content: center;
              align-items: center;
              gap: 4px;
              width: 95px;
              height: 30px;
              background: #f4f3ff;
              border-radius: 4px;
              font-size: 12px;
              color: #6271bc;
              cursor: pointer;
              &:hover {
                opacity: 0.8;
              }
            }
            .flie-close {
              cursor: pointer;
              &:hover {
                opacity: 0.8;
              }
            }
            /* 禁用状态样式 */
            .disabled-btn {
              cursor: not-allowed; /* 鼠标悬停时显示禁用状态 */
              opacity: 0.6; /* 降低透明度以表示不可点击 */
            }

            .disabled-btn:hover {
            }
          }
        }
      }
    }
  }
  .loading {
    .all-box {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 670px;
      .loading-img {
        animation: bounceai 2s ease-in-out infinite;
      }
      .loading-title {
        font-size: 22px;
        color: #34323d;
        margin: 44px 0 18px 0;
      }
      .loading-subtitle {
        font-size: 16px;
        color: #848387;
      }
    }
    @keyframes bounceai {
      0%,
      100% {
        /* 开始和结束位置 */
        transform: translateY(0px);
      }
      50% {
        /* 中间点位置 */
        transform: translateY(-10px);
      }
    }
  }
  .my-dialog {
    padding: 50px 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 37px;
    .my-dialog-title {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 14px;
      color: #727272;
    }
    .my-dialog-content {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
}
</style>